package com.example.java_chatroom.controller;

import com.example.java_chatroom.constant.Constants;
import com.example.java_chatroom.model.UserInfo;
import com.example.java_chatroom.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request){
        //1.首先，根据输入的名字取数据查询
        UserInfo userInfo=userInfoService.selectByName(username);
        //2.接着在根据密码是否正确
        if(userInfo==null || !password.equals(userInfo.getPassword())){
            System.out.println("登录失败"+userInfo);
            return new UserInfo();
        }
        //3.登录成功，就创建会话
        //true:如果没有回话，会创建并返回一个新对话
        //false:仅仅返回请求关联的会话对象，如果不存在，则返回null
        HttpSession session=request.getSession(true);
        session.setAttribute(Constants.USER_SESSION,userInfo);
        //返回useInfo之前，将密码干掉
        userInfo.setPassword("");
        return userInfo;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        UserInfo userInfo=null;
        try {
            userInfo=new UserInfo();
            userInfo.setUsername(username);
            userInfo.setPassword(password);
            userInfoService.insertUser(userInfo);
        } catch (DuplicateKeyException e) {
            //用户名出现重复情况，注册失败
            userInfo=new UserInfo();
            System.out.println("注册失败"+userInfo);
            e.printStackTrace();
        }
        userInfo.setPassword("");
        return userInfo;
    }

    @GetMapping("/getUserInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
        //1.从请求中获取会话
        HttpSession session=request.getSession(false);
        if(session==null){
            log.info("[getUserInfo]未获取到会话");
            return new UserInfo();
        }
        //2.从会话中获取用户信息
        UserInfo userInfo=(UserInfo) session.getAttribute(Constants.USER_SESSION);
        if(userInfo==null){
            log.info("[getUserInfo]未获取到用户信息");
            return new UserInfo();
        }
        userInfo.setPassword("");
        return userInfo;
    }
}
